package cn.regexp.web.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.regexp.domain.ShopStudent;
import cn.regexp.domain.ShopUser;
import cn.regexp.domain.UserInfo;
import cn.regexp.model.WxLoginModel;
import cn.regexp.redis.service.IShopUserRedisService;
import cn.regexp.service.IShopUserService;
import cn.regexp.service.IStudentService;
import cn.regexp.util.ApiBaseAction;
import cn.regexp.util.ApiUserUtils;
import cn.regexp.util.CommonUtil;
import cn.regexp.utils.CharUtil;
import cn.regexp.utils.JsonResult;
import cn.regexp.web.model.UserInfoModel;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController extends ApiBaseAction {
    @Autowired
    private IShopUserService userService;
    @Autowired
    private IStudentService studentService;
    @Autowired
    private IShopUserRedisService userRedisService;

    @PostMapping("/users/wxLogin")
    @ApiOperation(value = "微信登录", notes = "微信登录")
    public JsonResult<Object> wxLogin(@RequestBody WxLoginModel model) {
        // 获取请求 URL
        String requestUrl = ApiUserUtils.getWebAccess(model.getCode());
        // 获取 sessionData
        JSONObject sessionData = CommonUtil.httpsRequest(requestUrl, "GET", null);
        // 从请求参数中获取用户信息
        UserInfo userInfo = model.getUserInfo();
        // 获取 openid
        String openid = sessionData.getString("openid");
        Date nowTime = new Date();
        // 查询该用户是否已经注册
        ShopUser user = userService.queryByOpenId(openid);
        if (ObjectUtils.isEmpty(user)) {
            user = new ShopUser();
            user.setUsername("微信用户" + CharUtil.getRandomString(12));
            user.setPassword(openid);
            user.setRegisterTime(nowTime);
            user.setRegisterIp(this.getClientIp());
            user.setLastLoginTime(nowTime);
            user.setLastLoginIp(this.getClientIp());
            user.setWeixinOpenId(openid);
            user.setHeadImage(userInfo.getAvatarUrl());
            user.setGender(userInfo.getGender());
            user.setNickname(userInfo.getNickName());
            userService.save(user);
        } else {
            UpdateWrapper<ShopUser> wrapper = new UpdateWrapper<>();
            wrapper.set("last_login_ip", this.getClientIp())
                    .set("last_login_time", nowTime);
            userService.update(wrapper);
        }
        // 获取 token
        String token = CharUtil.getRandomString(32);
        // 将用户信息保存到 redis 中
        userRedisService.setToken(token, JSON.toJSONString(user));
        Map<String, Object> resultObj = new HashMap<>();
        resultObj.put("token", token);
        resultObj.put("userInfo", userInfo);
        resultObj.put("userId", user.getId());
        return JsonResult.success(resultObj);
    }

    @GetMapping("/users/getUserInfo")
    @ApiOperation(value = "获取用户信息", notes = "获取用户信息")
    public JsonResult<UserInfoModel> getUserInfo(Long userId) {
        UserInfoModel userInfo = new UserInfoModel();
        ShopUser user = userService.getById(userId);
        if (ObjectUtil.isEmpty(user)) {
            return JsonResult.error(0, "不存在该用户！", null);
        }
        userInfo.setGender(user.getGender());
        userInfo.setMobile(user.getMobile());
        userInfo.setNickname(user.getNickname());

        QueryWrapper<ShopStudent> wrapper = new QueryWrapper<>();
        wrapper.eq("is_del", ShopStudent.NO)
                .eq("is_bind", ShopStudent.YES)
                .eq("user_id", userId);
        ShopStudent student = studentService.getOne(wrapper);
        if (ObjectUtil.isNotEmpty(student)) {
            userInfo.setStudentNo(student.getStudentNo());
        }
        return JsonResult.success(userInfo);
    }

    @PostMapping("/users/unbind")
    @ApiOperation(value = "解绑学号", notes = "解绑学号")
    public JsonResult<String> unbind(@RequestBody UserInfoModel model) {
        try {
            if (checkParam(model)) return JsonResult.error(0, "信息有误，请联系管理员！", null);
            QueryWrapper<ShopStudent> wrapper = new QueryWrapper<>();
            wrapper.eq("student_no", model.getStudentNo())
                    .eq("is_del", ShopStudent.NO)
                    .eq("is_bind", ShopStudent.YES);
            ShopStudent student = studentService.getOne(wrapper);
            if (ObjectUtil.isNotEmpty(student)) {
                if (!model.getPassword().equals(student.getPassword())) {
                    return JsonResult.error(0, "密码错误", null);
                }
                student.setIsBind(ShopStudent.NO);
                studentService.updateById(student);
            }
            return JsonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResult.error(0, "解绑失败", null);
    }


    @PostMapping("/users/bind")
    @ApiOperation(value = "绑定学号", notes = "绑定学号")
    public JsonResult<String> bind(@RequestBody UserInfoModel model) {
        try {
            if (checkParam(model)) return JsonResult.error(0, "信息有误，请联系管理员！", null);
            QueryWrapper<ShopStudent> wrapper = new QueryWrapper<>();
            wrapper.eq("student_no", model.getStudentNo())
                    .eq("is_del", ShopStudent.NO)
                    .eq("is_bind", ShopStudent.NO);
            ShopStudent student = studentService.getOne(wrapper);
            if (ObjectUtil.isEmpty(student)) {
                return JsonResult.error(0, "不存在该学号", null);
            }
            if (!model.getPassword().equals(student.getPassword())) {
                return JsonResult.error(0, "密码错误", null);
            }
            student.setIsBind(ShopStudent.YES);
            studentService.updateById(student);
            return JsonResult.success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResult.error(0, "绑定失败", null);
    }

    private boolean checkParam(UserInfoModel model) {
        return ObjectUtil.isEmpty(model) || ObjectUtil.isEmpty(model.getStudentNo()) || ObjectUtil.isEmpty(model.getPassword());
    }
}
